package com.xms.security.service;

import com.xms.core.org.UserContext;
import com.xms.security.identity.IAuthenticationService;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <p>
 * AuthenticationService
 * </p>
 *
 * @author migo
 * @since 2021/9/4
 */
@Service
public class AuthenticationService implements IAuthenticationService {
    private final static String USER_KEY = "user";

    @Override
    public UserContext getAuthenticatedUser(HttpServletRequest request) {
        HttpSession session = request.getSession(true);
        return (UserContext)session.getAttribute(USER_KEY);
    }

    @Override
    public boolean isAuthenticated(HttpServletRequest request){
        return request.isRequestedSessionIdValid();
        /*HttpSession session = request.getSession(true);
        Optional<Object> token = Optional.ofNullable(session.getAttribute(USER_KEY));
        return token.isPresent();*/
    }

    @Override
    public void signIn(HttpServletRequest request, UserContext user, boolean persistent) throws ServletException {
        HttpSession session = request.getSession(true);
        if(session != null) {
            session.removeAttribute(USER_KEY);
        }
        session.setAttribute(USER_KEY, user);
        //_request.changeSessionId();
    }

    @Override
    public void signOut(HttpServletRequest request) throws ServletException {
        HttpSession session = request.getSession(true);
        session.removeAttribute(USER_KEY);
        session.invalidate();
        request.logout();
    }

    @Override
    public String getId(HttpServletRequest request) {
        return request.getRequestedSessionId();
        /*HttpSession session = request.getSession(true);
        return session.getId();*/
    }
}
